<template>
    <el-card class="box-card">

        <el-tabs v-model="state.activeName" @tab-click="handleTabClick">
            <el-tab-pane label="备份数据库" name="backup">
                <el-row style="margin-bottom: 15px;">
                    <el-button type="primary" @click="handleBackup">备份数据库</el-button>
                    <el-button type="success" @click="handleRepairBatch" plain>优化所选</el-button>
                    <el-button type="warning" @click="handleOptimizeBatch" plain>修复所选</el-button>
                </el-row>

                <el-table :data="state.tablesData" :empty-text="state.empty">
                    <el-table-column type="selection" width="38" />
                    <el-table-column prop="name" label="表" show-overflow-tooltip />
                    <el-table-column prop="collation" label="编码" show-overflow-tooltip />
                    <el-table-column prop="engine" label="引擎" show-overflow-tooltip />
                    <el-table-column prop="rows" label="行数" show-overflow-tooltip />
                    <el-table-column prop="data_length" label="大小" show-overflow-tooltip>
                        <template #default="scope">
                            {{ byteConvert(scope.row.data_length) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="data_length" label="多余" show-overflow-tooltip>
                        <template #default="scope">
                            {{ byteConvert(scope.row.data_free) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="update_time" label="更新时间" width="168" align="center" />
                    <el-table-column fixed="right" label="操作" width="96" align="center">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleRepair(scope.row.name)" size="small">修复</el-button>
                            <el-button link type="primary" @click="handleOptimize(scope.row.name)"
                                size="small">优化</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="恢复数据库" name="restore">
                <el-row style="margin-bottom: 15px;">
                    <el-button type="danger" @click="handleDeleteBatch" plain>删除所选</el-button>
                </el-row>
                <el-table :data="state.filesData" :empty-text="state.empty">
                    <el-table-column type="selection" width="38" />
                    <el-table-column prop="name" label="名称" show-overflow-tooltip />
                    <el-table-column prop="ctime" label="备份时间" width="160" align="center">
                        <template #default="scope">
                            {{ timeConvert(scope.row.ctime) }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="96" align="center">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleRestore(scope.row.name)"
                                size="small">恢复</el-button>

                            <el-popconfirm title="确定要删除吗？" @confirm="handleDelete(scope.row.name)">
                                <template #reference>
                                    <el-button link type="primary" size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>

            </el-tab-pane>

            <el-tab-pane label="备份设置" name="config">

                <el-form :model="state.form" style="width: 300px;" label-width="68px">
                    <el-form-item label="备份目录">
                        <el-input v-model="state.form.path" :disabled="state.disabled" />
                    </el-form-item>

                    <el-form-item label="备份大小">
                        <el-input v-model="state.form.size" :disabled="state.disabled" />
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
        </el-tabs>


        <el-dialog v-model="state.progressVisible" width="600px">
            <template #header>
                备份数据库中...
            </template>
            <p style="margin-bottom: 20px">正在备份表...</p>
            <el-progress :text-inside="true" :stroke-width="22" :percentage="state.progress" status="success" />
        </el-dialog>


    </el-card>
</template>
<script setup>
import { reactive } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Request from '@/request'

const state = reactive({
    empty: '暂无数据',
    tablesData: [],
    filesData: [],
    tables: [],
    activeName: 'backup',
    progressVisible: false,
    disabled: false,
    table: '',
    progress: 0,
    form: {
        path: '',
        size: ''
    },
    timer: null
})

const handleTabClick = (tab) => {
    if (tab.index == 2) {
        getConfig()
    } else {
        const type = tab.index == 1 ? 'files' : 'tables'
        getDataList(type)
    }
}

const handleBackup = () => {
    Request
        .get('system/database/backup')
        .then(res => {
            if (res.code) {
                ElMessage.error(res.message)
            } else {
                state.progressVisible = true
                state.timer = setInterval(getProgress, 1000)
            }

        })
        .catch((error) => {
            console.log('error', error)
        })
}

const getProgress = () => {
    Request
        .get('system/database/progress')
        .then(res => {
            if (!res.code) {
                state.table = res.datas.table
                state.progress = res.datas.progress
                if (state.progress == 100) {
                    state.progressVisible = false
                    clearInterval(state.timer)
                    state.progress = 0
                    state.activeName = 'restore'
                    getDataList('files')
                }
            } else {
                clearInterval(state.timer)
                ElMessage.error(res.message)
            }
        })
        .catch((error) => {
            console.log("error", error)
        })
};

const getConfig = () => {
    Request
        .get('system/database/config')
        .then(res => {
            if (res.code) {
                state.disabled = true
            } else {
                state.form = res.datas
            }
        })
        .catch((error) => {
            console.log("error", error)
        })
}

const onSubmit = () => {
    Request
        .post('system/database/config', { field: state.form })
        .then(res => {
            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log("error", error)
        })
}

const handleRepairBatch = () => {

}

const handleOptimizeBatch = () => {

}

const handleDeleteBatch = () => {

}

const handleRepair = (tables) => {
    Request
        .post('system/database/repair', { tables: tables })
        .then((res) => {
            if (!res.code) {
                getDataList()
            }

            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const handleOptimize = (tables) => {
    Request
        .post('system/database/optimize', { tables: tables })
        .then((res) => {
            if (!res.code) {
                getDataList()
            }

            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const handleRestore = (name) => {
    Request
        .post('system/database/restore', { name: name })
        .then(res => {
            if (!res.code) {
                state.activeName = 'backup'
                getDataList('tables')
            }

            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const handleDelete = (name) => {
    Request
        .post('system/database/delete', { name: name })
        .then(res => {
            if (!res.code) {
                getDataList('files')
            }

            ElMessage({
                message: res.message,
                grouping: true,
                type: res.code ? 'error' : 'success'
            })
        })
        .catch((error) => {
            console.log('error', error)
        })
}

const byteConvert = (size) => {
    if (!size) return "";
    var num = 1024.00; //byte
    if (size < num)
        return size + " B";
    if (size < Math.pow(num, 2))
        return (size / num).toFixed(2) + " K"; //kb
    if (size < Math.pow(num, 3))
        return (size / Math.pow(num, 2)).toFixed(2) + " M"; //M
    if (size < Math.pow(num, 4))
        return (size / Math.pow(num, 3)).toFixed(2) + " G"; //G
    return (size / Math.pow(num, 4)).toFixed(2) + " T"; //T

}

const timeConvert = (time) => {
    var n = parseInt(time) * 1000
    var D = new Date(n)
    var year = D.getFullYear() //四位数年份

    var month = D.getMonth() + 1 //月份(0-11),0为一月份
    month = month < 10 ? '0' + month : month

    var day = D.getDate() //月的某一天(1-31)
    day = day < 10 ? '0' + day : day

    var hours = D.getHours() //小时(0-23)
    hours = hours < 10 ? '0' + hours : hours

    var minutes = D.getMinutes() //分钟(0-59)
    minutes = minutes < 10 ? '0' + minutes : minutes

    // var seconds = D.getSeconds();//秒(0-59)
    // seconds = seconds<10?('0'+seconds):seconds;
    // var week = D.getDay();//周几(0-6),0为周日
    // var weekArr = ['周日','周一','周二','周三','周四','周五','周六'];

    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
}

const getDataList = (type) => {
    Request
        .post('system/database/index', { type: type })
        .then((res) => {
            if (res.code) {
                state.empty = res.message
            } else {
                if (type == 'tables') {
                    state.tablesData = res.datas
                } else {
                    state.filesData = res.datas
                }

            }
        })
        .catch((error) => {
            console.log('error', error)
        })
}

getDataList('tables')
</script>
<style scoped></style>